<?php

namespace backend\models;

use Yii;
use Da\User\Model\User;
use backend\helpers\FileNameInflector;

/**
 * This is the model class for table "decree".
 *
 * @property int $id
 * @property string|null $title
 * @property string|null $date_signture
 * @property string|null $file_name
 * @property string|null $comment
 * @property int $id_type
 *
 * @property DecreeType $type
 */
class Decree extends \yii\db\ActiveRecord
{
    public $decreeFile;
    private $_liableUsersArr;
    private $_bucketName = 'ogikm-decree';

    const BUCKET_NAME = 'ogikm-decree';
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'decree';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['date_signature', 'date_before', 'liableUsersArr'], 'safe'],
            [['id_type'], 'required'],
            [['id_type'], 'integer'],
            [['title', 'file_name'], 'string', 'max' => 255],
            [['comment'], 'string', 'max' => 512],
            [['own_number'], 'string', 'max' => 12],
            [['id_type'], 'exist', 'skipOnError' => true, 'targetClass' => DecreeType::className(), 'targetAttribute' => ['id_type' => 'id']],
            [['decreeFile'], 'file', 'extensions' => 'doc, docx, pdf'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'Название',
            'date_signature' => 'Дата подписания',
            'date_before' => 'Дата окончания',
            'file_name' => 'Файл приказа',
            'own_number' => 'Номер приказа',
            'comment' => 'Комментарий',
            'id_type' => 'Тип',
            'decreeFile' => 'Приказ',
            'liableUsersArr' => 'Ответственные сотрудники'
        ];
    }

    /**
     * Gets query for [[Type]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getType()
    {
        return $this->hasOne(DecreeType::className(), ['id' => 'id_type']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getLiableUsers()
    {
        return $this->hasMany(User::className(), ['id' => 'user_id'])->viaTable('{{%decree_user}}', ['decree_id' => 'id']);
    }

    public function getLiableUsersArr()
    {
        if ($this->_liableUsersArr === null) 
        {
            $this->_liableUsersArr = $this->getLiableUsers()->select('id')->column();
        }
        return $this->_liableUsersArr;
    }

    public function setLiableUsersArr($value)
    {
        $this->_liableUsersArr = (array)$value;
        print_r($this->_liableUsersArr);
    }

    public function afterSave($insert, $changedAttributes)
    {
        $this->updateLiableUsers();
        parent::afterSave($insert, $changedAttributes);
    }
    
    public function beforeSave($insert)
    {
        if (!parent::beforeSave($insert)) {
            return false;
        }

        // Запись новая
        if($insert)
        {
            // Спокойно сохраняем все файлы
            $this->insertDecree();
        }
        // Запись обновляется
        else
        {
            // Необходимы дополнительные проверки
            $this->updateDecree();
        }
        
        return true;
    }

    public function beforeDelete()
    {
        if (!parent::beforeDelete()) {
            return false;
        }

        $this->deleteDecree();

        return true;
    }

    private function updateLiableUsers()
    {
        $currentLiableUserIds = $this->getLiableUsers()->select('id')->column();
        $newLiableUserIds = $this->getLiableUsersArr();

        foreach (array_filter(array_diff($newLiableUserIds, $currentLiableUserIds)) as $userId) 
        {
            if ($user = User::findOne($userId)) 
            {
                $this->link('liableUsers', $user);
            }
        }

        foreach (array_filter(array_diff($currentLiableUserIds, $newLiableUserIds)) as $userId) 
        {
            if ($user = User::findOne($userId)) 
            {
                $this->unlink('liableUsers', $user, true);
            }
        }
    }

    public function insertDecree()
    {
        if($this->decreeFile)
        {
            $s3 = Yii::$app->get('s3');

            $generatedName = 'Приказ №' 
                . FileNameInflector::specialSlug($this->own_number) . ' ' 
                . FileNameInflector::specialSlug($this->title) 
                . '.' . $this->decreeFile->extension;
    
            $result = $s3->commands()->upload($generatedName, $this->decreeFile->tempName)->inBucket($this->_bucketName)->withAcl('private')->execute();
            
            $this->file_name = $generatedName;
        }
    }

    public function updateDecree()
    {
        if($this->decreeFile)
        {
            if($this->file_name)
            {
                $this->deleteDecree();
            }
            $this->insertDecree();
        }
    }

    public function deleteDecree()
    {
        if($this->file_name)
        {
            $s3 = Yii::$app->get('s3');
            $s3->commands()->delete($this->file_name)->inBucket($this->_bucketName)->execute();
        }
    }

}
